package com.wx.md.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wx.md.dao.SysUserDao;
import com.wx.md.tb.SysUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Deprecated
@Component("shiroAuthorizingRealm")
public class ShiroAuthorizingRealm extends AuthorizingRealm {


    @Autowired
    SysUserDao sysUserDao;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser sysUser =    (SysUser) principalCollection.getPrimaryPrincipal();
        //根据获得的用户获得用户的权限
        //资源：操作：id user:create:用户id
        List<String> premissionList = new ArrayList<>();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(premissionList);
        return simpleAuthorizationInfo;
    }

    /**
     * cation 身份认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       String userName =  authenticationToken.getPrincipal().toString();
       //去数据库中，根据用户名查找用户
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name",userName);
        List<SysUser> selectList = sysUserDao.selectList(queryWrapper);
        if(selectList.size()<=0){
            System.out.println("用户名不存在");
        }
        SysUser sysUser = selectList.get(0);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser,sysUser.getPassword(),this.getName());
        return info;
    }
}
